<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input v-model="listQuery.keyWord" size="small" placeholder="请输入关键词" clearable class="filter-item w-200" />
      <!-- <el-button-group class="filter-item"> -->
        <el-button size="small" type="primary" icon="el-icon-search" @click="search">搜索</el-button>
        <el-button size="small" icon="el-icon-refresh" @click="refresh">重置</el-button>
        <el-button size="small" type="primary" plain icon="el-icon-plus" @click="add">新增</el-button>
      <!-- </el-button-group> -->
    </div>
    <el-table v-loading="listLoading" :data="tableData" element-loading-text="Loading" border fit height="630px" class="table-container" highlight-current-row>
      <el-table-column fixed label="序号" width="80" align="center">
        <template slot-scope="scope">
          <span>{{ (listQuery.pageNo - 1) * listQuery.pageSize + scope.$index + 1 }}</span>
        </template>
      </el-table-column>
      <el-table-column label="角色编号" align="center">
        <template slot-scope="scope">
          {{ scope.row.code }}
        </template>
      </el-table-column>
      <el-table-column label="角色名称" align="center">
        <template slot-scope="scope">
          {{ scope.row.name }}
        </template>
      </el-table-column>
      <!-- <el-table-column label="状态" width="80" align="center">
        <template slot-scope="scope">
          <el-switch :value="scope.row.status" :active-value="1" :inactive-value="0" @change="changeStatus($event, scope)" />
        </template>
      </el-table-column> -->
      <el-table-column fixed="right" label="操作" width="200" align="center">
        <template slot-scope="scope">
          <div class="operate_area">
            <img src="@/assets/icon/edit.png" alt="" class="edit" @click="edit(scope)" />
            <img src="@/assets/icon/delete.png" alt="" class="delete" @click="del(scope)" />
          </div>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      style="margin-top: 20px"
      v-show="total > 0"
      :total="total"
      :page.sync="listQuery.pageNo"
      :limit.sync="listQuery.pageSize"
      @pagination="fetchData"
    />
    <el-dialog :visible.sync="dialogVisible" :title="dialogType === 'modify' ? '修改' : '新增'">
      <el-form ref="dataForm" :model="formData" :rules="rules" label-width="120px" label-position="right">
        <el-form-item label="角色编号" prop="code">
          <el-input v-model="formData.code" placeholder="请输入角色编号" />
        </el-form-item>
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入角色名称" />
        </el-form-item>
        <el-form-item label="菜单权限">
          <el-checkbox v-model="menuExpand" @change="handleCheckedTreeExpand($event, 'menu')">展开/折叠</el-checkbox>
          <el-checkbox v-model="menuNodeAll" @change="handleCheckedTreeNodeAll($event, 'menu')">全选/全不选</el-checkbox>
          <el-checkbox v-model="menuCheckStrictly" @change="handleCheckedTreeConnect($event, 'menu')">父子联动</el-checkbox>
          <el-tree
            class="tree-border"
            :data="menuOptions"
            :default-checked-keys="menuOptions_selset"
            show-checkbox
            ref="menu"
            node-key="id"
            :check-strictly="!menuCheckStrictly"
            empty-text="加载中，请稍后"
            :props="defaultProps"
          ></el-tree>
        </el-form-item>
      </el-form>
      <div class="text-right">
        <el-button type="danger" @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submit">确定</el-button>
      </div>
      
    </el-dialog>
  </div>
</template>

<script>
import { getRoleList, addRole, updateRole, deleteRole, getUserMenuTreeSelect } from '@/http/api/myHttp.js'

export default {
  components: {},
  data() {
    return {
      formData: {},
      total: 0,
      tableData: [],
      menus: [],
      listLoading: false,
      listQuery: {
        pageNo: 1,
        pageSize: 20,
        keyWord: null
      },
      dialogVisible: false,
      dialogType: 'create',
      loading: false,
      defaultMenuProps: {
        children: 'children',
        label: 'title'
      },
      // 菜单列表
      menuOptions: [],
      menuOptions_selset: [],
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      menuCheckStrictly: true,
      deptCheckStrictly: true,
      menuExpand: false,
      menuNodeAll: false,
      deptExpand: true,
      deptNodeAll: false,
      // 表单校验
      rules: {
        code: [{ required: true, message: '角色编号不能为空', trigger: 'blur' }],
        name: [{ required: true, message: '角色名称不能为空', trigger: 'blur' }]
      }
    }
  },
  created() {
    this.fetchData()
  },
  methods: {
    search() {
      this.fetchData()
    },
    refresh() {
      this.listQuery = {
        pageNo: 1,
        pageSize: 10,
        keyWord: null
      }
      this.fetchData()
    },
    // 表单重置
    reset() {
      if (this.$refs.menu) {
        this.$refs.menu.setCheckedKeys([])
      }
      this.formData = {
        code: null,
        name: null
      }
      this.menuExpand = false
      this.menuNodeAll = false
      this.deptExpand = true
      this.deptNodeAll = false
      this.menuCheckStrictly = true
      this.deptCheckStrictly = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    fetchData() {
      this.listLoading = true
      getRoleList(this.listQuery).then((res) => {
        this.listLoading = false
        if (res.code == 0) {
          this.tableData = res.data.records
          this.total = res.data.total
        }
      })
    },
    fetchMenu(scope) {
      var obj
      if (scope) {
        obj = {
          roleId: scope.row.objectid || ''
        }
      } else {
        obj = {
          roleId: ''
        }
      }
      getUserMenuTreeSelect(obj).then((res) => {
        if (res.code == 0) {
          this.menuOptions = res.data.menus
          this.menuOptions_selset = res.data.checkedKeys
        }
      })
      /* getMenu().then(response => {
					this.menus = response.data.list
				}) */
    },
    add() {
      this.reset()
      this.fetchMenu() //获取菜单
      this.dialogVisible = true
      this.dialogType = 'create'
    },
    edit(scope) {
      this.reset()
      this.fetchMenu(scope) //获取菜单
      this.formData = JSON.parse(JSON.stringify(scope.row))
      this.dialogVisible = true
      this.dialogType = 'modify'
    },
    // 树权限（展开/折叠）
    handleCheckedTreeExpand(value, type) {
      if (type == 'menu') {
        let treeList = this.menuOptions
        for (let i = 0; i < treeList.length; i++) {
          this.$refs.menu.store.nodesMap[treeList[i].id].expanded = value
        }
      } else if (type == 'dept') {
        let treeList = this.deptOptions
        for (let i = 0; i < treeList.length; i++) {
          this.$refs.dept.store.nodesMap[treeList[i].id].expanded = value
        }
      }
    },
    // 树权限（全选/全不选）
    handleCheckedTreeNodeAll(value, type) {
      if (type == 'menu') {
        this.$refs.menu.setCheckedNodes(value ? this.menuOptions : [])
      } else if (type == 'dept') {
        this.$refs.dept.setCheckedNodes(value ? this.deptOptions : [])
      }
    },
    // 树权限（父子联动）
    handleCheckedTreeConnect(value, type) {
      if (type == 'menu') {
        this.menuCheckStrictly = value ? true : false
      } else if (type == 'dept') {
        this.deptCheckStrictly = value ? true : false
      }
    },
    // changeStatus(value, scope) {
    //   setTimeout(() => {
    //     this.list[scope.$index].status = value
    //     this.$message({
    //       message: '更新成功',
    //       type: 'success'
    //     })
    //   }, 300)
    // },
    del(scope) {
      this.$confirm(`确认删除该条数据吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          var obj = {
            objectid: scope.row.objectid
          }
          const loading = this.$loading({
            lock: true,
            text: '正在删除...',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.5)'
          })
          deleteRole(obj).then((res) => {
            loading.close()
            if (res.code == 0) {
              this.$message({
                message: '删除成功',
                type: 'success'
              })
              this.fetchData()
            }
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    // 所有菜单节点数据
    getMenuAllCheckedKeys() {
      // 目前被选中的菜单节点
      let checkedKeys = this.$refs.menu.getCheckedKeys()
      // 半选中的菜单节点
      let halfCheckedKeys = this.$refs.menu.getHalfCheckedKeys()
      checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys)
      return checkedKeys
    },
    submit() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const loading = this.$loading({
            lock: true,
            text: '正在提交...',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.5)'
          })
          let menusData_str
          let menusData = this.getMenuAllCheckedKeys()
          if (menusData.length > 0) {
            menusData_str = menusData.join(',')
          }
          if (this.dialogType == 'create') {
            var obj = {
              code: this.formData.code,
              name: this.formData.name,
              menus: menusData_str || ''
            }
            addRole(obj).then((res) => {
              loading.close()
              if (res.code == 0) {
                this.dialogVisible = false
                this.$message({
                  message: '提交成功',
                  type: 'success'
                })
                this.fetchData()
              }
            })
          } else {
            var obj = {
              objectid: this.formData.objectid,
              code: this.formData.code,
              name: this.formData.name,
              menus: menusData_str || ''
            }
            updateRole(obj).then((res) => {
              loading.close()
              if (res.code == 0) {
                this.dialogVisible = false
                this.$message({
                  message: '修改成功',
                  type: 'success'
                })
                this.fetchData()
              }
            })
          }
        }
      })
    },
    getMenu(scope) {}
  }
}
</script>
<style lang="scss" scoped>
.app-container {
  box-sizing: border-box;
  width: 100%;
  height: 100%;
}
.filter-container {
  display: flex;
  justify-content: flex-start;
}

.filter-item {
  width: 300px;
  margin-right: 10px;
}

.el-table {
  ::v-deep {
    margin-top: 20px;
    .el-table__header {
      border-radius: 6px;
      overflow: hidden;
    }
    .el-table__cell {
      height: 50px;
      padding: 0;
    }

    .is-leaf {
      background-image: linear-gradient(to top, rgba(128, 191, 255, 1), rgba(51, 153, 255, 1));
      font-size: 14px;
      font-weight: 700;
      letter-spacing: 0px;
      line-height: 24px;
      color: rgba(255, 255, 255, 1);
      border-right: 1px solid white;
    }
  }
}

.operate_area {
  width: 80px;
  display: flex;
  justify-content: space-between;
  margin: 0 auto;
  img {
    cursor: pointer;
  }
}
</style>
